import consultasBD
import model2DtoFactory
import dto2ModelFactory
import model
import sellManager
import sincronizar_tabla
import utiles
import sussanException

import uuid
import math

NO_SOLICITADA = "NO SOLICITADA"
PENDIENTE = "PENDIENTE"
EN_IMPRESION = "EN IMPRESION"
IMPRESA = "IMPRESA"
ENTREGADA = "ENTREGADA"

def get_club(club_id):
    s = model.create_session()
    clubModel = s.query(model.Club).get(club_id)
    if clubModel:
        return model2DtoFactory.create_club(clubModel)
        
    return None
    
def get_club_list(estado):
    ret = []
    s = model.create_session()
    for c in s.query(model.Club).filter_by(estado=estado).all():
        ret.append(model2DtoFactory.create_club(c))
    return ret

def request_card(client_id):
    s = model.create_session()
    state = PENDIENTE
    if s.query(model.Club).filter_by(idcliente=client_id).count() == 0:
        sucursal = s.query(model.Sucursal).filter_by(activa=1).one()        
        card_number = utiles.number_generator(sucursal.idsucursal)
        while s.query(model.Club).get(card_number):
            card_number = utiles.number_generator(sucursal.idsucursal)
        
        category = 1        
        sql = "INSERT INTO club VALUES('%s','%s','%s','%s',%s,%s,'%s')" % (card_number, client_id, category, state, 'CURRENT_TIMESTAMP', 'CURRENT_TIMESTAMP', sucursal.idsucursal)
    else:
        clubModel = s.query(model.Club).filter_by(idcliente=client_id).one()
        sql = "UPDATE club SET estado = '%s' WHERE id = '%s'" % (state, clubModel.id)
        
    print sql
    consultasBD.executaSinCommit(None, sql)
    sincronizar_tabla.addChange(sql=sql)

def is_client_waiting_for_card(client_id):
    s = model.create_session() 
    if s.query(model.Club).filter_by(idcliente=client_id).filter(model.Club.estado.in_([PENDIENTE, EN_IMPRESION, IMPRESA])).count() == 1:
        return True
    else:
        return False

def is_client_in_club(client_id):        
    s = model.create_session() 
    if s.query(model.Club).filter_by(idcliente=client_id).filter(model.Club.estado.in_([PENDIENTE, EN_IMPRESION, IMPRESA, ENTREGADA])).count() == 1:
        return True
    else:
        return False

def get_card_state(club_id):
    s = model.create_session()
    club = s.query(model.Club).get(club_id)
    return club.estado    
        
def mark_card_as_printing(club_id):
    __change_card_state(club_id, EN_IMPRESION)

def mark_card_as_printed(club_id):
    __change_card_state(club_id, IMPRESA)

def mark_card_as_delivered(club_id):
    #TODO: VALIDACIONES
    __change_card_state(club_id, ENTREGADA)

def mark_card_as(club_id, state):
    __change_card_state(club_id, state)

def __change_card_state(club_id, state):
    sql = "UPDATE club SET estado='%s' WHERE id = '%s'" % (state, club_id)
    consultasBD.executaSinCommit(None, sql)
    sincronizar_tabla.addChange(sql=sql)

def find_card_number(client_id):
    s = model.create_session()
    result = s.query(model.Club).filter_by(idcliente=client_id) 
    if result.count() == 0: return None
    
    return result.one().id
    
def clean_club_id(club_id):
    return club_id.replace("-", "")
    
def find_client_id(club_id):
    s = model.create_session()
    result = s.query(model.Club).get(club_id) 
    if not result: return None
    
    return result.idcliente
    
def get_formatted_card_number(club_id):
    return "%s-%s-%s-%s" % (club_id[0:4], club_id[4:8], club_id[8:12], club_id[12:16])
     
def save_sell_points(club_id, idventa, observations):
    client_id = find_client_id(club_id)
    venta = sellManager.get_sell(idventa)
    nrofactura = venta.nro_factura
    
    new_points = earned_points(club_id, venta.total)
    
    pagos_club = sellManager.get_sell_pagos_by_type(idventa, 'CL')
    spent_points = 0
    for p in pagos_club:
        spent_points += money_to_points(club_id, p.monto)
    
    prev_saldo = get_saldo(club_id)
    if spent_points > prev_saldo:
        raise sussanException.SussanException("Puntos insuficientes para realizar el pago")
    
    total_points = new_points - spent_points
    saldo = prev_saldo + total_points
    
    sql = "INSERT INTO club_puntos VALUES('%s', '%s','%s','%s','%s',%s,'%s','%s','%s','%s','%s')" % (uuid.uuid1(), club_id, client_id, nrofactura, venta.total, 'CURRENT_TIMESTAMP', new_points, spent_points, total_points, saldo, observations)
    print sql
    consultasBD.executaSinCommit(None, sql)
    sincronizar_tabla.addChange(sql=sql)

'''
En el futuro podria leer el valor de conversion de dinero/puntos de una tabla de configuracion
En el futuro se podria tener en cuenta la categoria del cliente para asignar puntos
'''

def money_to_points(club_id, money):
    return int(float(money) / .04)

def points_to_money(club_id, points):
    return float(points * .04)
   
def earned_points(club_id, money):
    return int(math.ceil(money / 2))
    
def get_saldo(club_id):
    s = model.create_session()
    result = s.query(model.ClubPuntos).filter_by(idclub=club_id).order_by(model.ClubPuntos.fecha.desc()).all()
    if not result: return 0
    
    return int(result[0].saldo)
    
    

